/*
 * @Author: fanjs
 * @Date: 2025-02-09 20:41:55
 * @Description: 路由
 */
import React from 'react';
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { AnimatePresence } from 'framer-motion';
import AppLayout from '@/components/Layout';
import Home from '../pages/Home';
import Company from '../pages/Company';
import Login from '../pages/Login';
import NotFound from '../pages/NotFound';

// 邮件分发
import EmailConfig from '../pages/Distribute/config';
import EmailContent from '../pages/Distribute/content';
import EmailRecipients from '../pages/Distribute/recipients';
import EmailRecord from '../pages/Distribute/record';

import { localStg } from '@/utils/storage';
import PageTransition from '@/components/PageTransition';

const RequireAuth = ({ children }: { children: React.ReactElement }) => {
  const location = useLocation();
  const token = localStg.get('token');

  if (!token) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
};

const RequireGuest = ({ children }: { children: React.ReactElement }) => {
  const token = localStg.get('token');

  if (token) {
    return <Navigate to="/" replace />;
  }

  return children;
};

const AppRouter: React.FC = () => {
  const location = useLocation();

  return (
    <AnimatePresence mode="wait">
      <Routes location={location} key={location.pathname}>
        <Route path="/login" element={<RequireGuest><PageTransition><Login /></PageTransition></RequireGuest>} />
        <Route path="/" element={<RequireAuth><AppLayout /></RequireAuth>}>
          <Route index element={<PageTransition><Home /></PageTransition>} />
          <Route path="/distribute" element={<PageTransition><EmailConfig /></PageTransition>} />
          <Route path="/distribute/content" element={<PageTransition><EmailContent /></PageTransition>} />
          <Route path="/distribute/recipients/:task_id" element={<PageTransition><EmailRecipients /></PageTransition>} />
          <Route path="/distribute/record/:task_id" element={<PageTransition><EmailRecord /></PageTransition>} />
        </Route>
        {/* 公司简介 - 不需要登录即可访问 */}
        <Route path="/company" element={<PageTransition><Company /></PageTransition>} />
        <Route path="*" element={<PageTransition><NotFound /></PageTransition>} />
      </Routes>
    </AnimatePresence>
  );
};

export default AppRouter;
